package io.traveller.common.mybatis;

import com.google.common.base.CaseFormat;

import java.util.Arrays;

/**
 * Mybatis单表查询返回字段封装
 * 默认: 将驼峰转换成下换线规则.
 * 比如: "orderCount" 转换为 "order_count"
 *
 * Created by yunai on 16/8/4.
 */
public class Field {

    public static final String ID_FIELD_NAME = "id";
    public static final Field ID = new Field(ID_FIELD_NAME);

    private final String[] fields;

    // todo 未来可以做对象池
    public Field(String... fields) {
        this.fields = fields;
        convertCamelCaseToUnderscore(this.fields);
    }

    /**
     * 将字段数组中的驼峰转换成下划线规则.
     * 比如: "orderCount" 转换为 "order_count"
     *
     * @param fields 字段数组
     */
    private void convertCamelCaseToUnderscore(String... fields) {
        for (int i = 0, len = fields.length; i < len; i++) {
            fields[i] = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fields[i]);
        }
    }

    public String[] get() {
        if (null == fields || fields.length == 0) {
            return new String[]{"*"};
        }
        return fields;
    }

    @Override
    public boolean equals(Object oo)   {
        Field field = (Field) oo;
        return Arrays.deepEquals(field.get(), fields);
    }

}
